/**
 * Created by TRwin7SP1 on 2016/8/10.
 */

$(document).ready(function() {

    // image enable the dicomImage element
    var element = $('#dicomImage').get(0);
    cornerstone.enable(element);

    //load the image and display it
    var imageId = 'example://1';
    cornerstone.loadImage(imageId).then(function(image) {
        cornerstone.displayImage(element, image);
    });

    // Add event handlers to zoom the image in and out
    $('#zoomIn').click(function (e) {
        var viewport = cornerstone.getViewport(element);
        viewport.scale += 0.25;
        cornerstone.setViewport(element, viewport);
    });
    $('#zoomOut').click(function (e) {
        var viewport = cornerstone.getViewport(element);
        viewport.scale -= 0.25;
        cornerstone.setViewport(element, viewport);
    });
    $('#reset').click(function (e) {
        cornerstone.reset(element);
    });

    // add event handlers to pan image on mouse move
    $('#dicomImage').mousedown(function (e) {
        var lastX = e.pageX;
        var lastY = e.pageY;


        $(document).mousemove(function (e) {
            var deltaX = e.pageX - lastX,
                deltaY = e.pageY - lastY;
            lastX = e.pageX;
            lastY = e.pageY;

            var viewport = cornerstone.getViewport(element);
            viewport.translation.x += (deltaX / viewport.scale);
            viewport.translation.y += (deltaY / viewport.scale);
            cornerstone.setViewport(element, viewport);
        });

        $(document).mouseup(function (e) {
            $(document).unbind('mousemove');
            $(document).unbind('mouseup');
        });
    });

    $('#dicomImage').on('mousewheel DOMMouseScroll', function (e) {
        // Firefox e.originalEvent.detail > 0 scroll back, < 0 scroll forward
        // chrome/safari e.originalEvent.wheelDelta < 0 scroll back, > 0 scroll forward
        if (e.originalEvent.wheelDelta < 0 || e.originalEvent.detail > 0) {
            var viewport = cornerstone.getViewport(element);
            viewport.scale -= 0.25;
            cornerstone.setViewport(element, viewport);
        } else {
            var viewport = cornerstone.getViewport(element);
            viewport.scale += 0.25;
            cornerstone.setViewport(element, viewport);
        }
        //prevent page fom scrolling
        return false;
    });
});
